package com.google.gwt.gwtpages.client.page.loader;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.google.gwt.gwtpages.client.message.exceptions.PageNotFoundException;
import com.google.gwt.gwtpages.client.page.GWTPage;
import com.google.gwt.gwtpages.client.page.GWTPageAttributes;
import com.google.gwt.gwtpages.client.page.GWTPagesPresenter;

/**
 * Simple {@link GWTPagesLoader} implementation. {@link GWTPagesPresenter} instances are
 * registered for specific page tokens.
 * 
 * @author Joe Hudson
 */
public abstract class SimplePageLoader implements GWTPagesLoader {

	private Map<String, GWTPagesPresenter> pages = new HashMap<String, GWTPagesPresenter>();
	private Map<String, GWTPageAttributes> metaData = new HashMap<String, GWTPageAttributes>();

	/**
	 * Register the page implementation
	 * 
	 * @param pageToken
	 *            the page token
	 * @param page
	 *            the page implementation
	 * @return this for chaining
	 */
	public SimplePageLoader registerPage(String pageToken, GWTPagesPresenter page) {
		return registerPage(pageToken, page, null);
	}

	/**
	 * Register the page implementation
	 * 
	 * @param pageToken
	 *            the page token
	 * @param page
	 *            the page implementation
	 * @param metaData
	 *            the {@link GWTPageAttributes}
	 * @return this for chaining
	 */
	public SimplePageLoader registerPage(String token, GWTPagesPresenter page,
			GWTPageAttributes metaData) {
		pages.put(token, page);
		if (null != metaData)
			this.metaData.put(token, metaData);
		return this;
	}

	public boolean isValidPageToken(String token) {
		return (null != pages.get(token));
	}

	public Iterator<String> getValidPageTokens() {
		return pages.keySet().iterator();
	}
	
	public void getPage(String pageToken, PageLoadCallback pageHandler) {
		GWTPagesPresenter p = pages.get(pageToken);
		if (null != p) {
			pageHandler.onPageFound(new GWTPage(pageToken, p, metaData
					.get(pageToken), this));
		} else {
			pageHandler.onPageNotFound(pageToken);
		}
	}

	public GWTPageAttributes getMetaData(String token) throws PageNotFoundException {
		return metaData.get(token);
	}
}